//
//  XNoteBookListViewController.m
//  iPlan
//
//  Created by 侯伟 on 2021/9/7.
//

#import "XNoteBookListViewController.h"
#import "RSRefreshTableView.h"
#import "XNoteBookTableViewCell.h"
#import <LYEmptyView/LYEmptyView.h>
#import <LYEmptyView/UIView+Empty.h>

#import "XNoteBook.h"
#import "XNoteBookDetailViewController.h"
#import "XNoteBookEditViewController.h"

@interface XNoteBookListViewController ()<UITableViewDelegate,UITableViewDataSource>

//@property(nonatomic,strong) MyLinearLayout *contentLayout;

/// 影片
@property(nonatomic,strong)RSRefreshTableView* tableView;

//底部
@property(nonatomic,strong) MyLinearLayout *bottomLayout;

//编辑
@property(nonatomic,strong) UIButton* editBtn;

//全选
@property(nonatomic,strong) UIButton* allBtn;

//删除
@property(nonatomic,strong) UIButton* delBtn;

//添加
@property(nonatomic,strong) UIButton* addBtn;

//data
@property(nonatomic,strong)NSMutableArray* noteBooks;

@end

@implementation XNoteBookListViewController

- (BOOL)isTableEditing{
    if(self.editBtn){
        return self.editBtn.selected;
    }
    return NO;
}

- (void)loadView{
    [super loadView];
    self.view.backgroundColor = UIColor.whiteColor;
    
//    // 线性布局
//    MyLinearLayout *contentLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Vert)];
//    contentLayout.myMargin = 0;
//    [self.view addSubview:contentLayout];
//    _contentLayout = contentLayout;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupNavBar];
    
    [self setupSubView];
    
    [self reloadData];
}

- (void)setupNavBar{
    self.navigationItem.title = @"记事本";
    
//    UIButton* editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [editBtn setTitle:@"编辑" forState:UIControlStateNormal];
//    [editBtn setTitle:@"取消" forState:UIControlStateSelected];
//    [editBtn setTitleColor:COLOR_WHITE forState:UIControlStateNormal];
//    [editBtn addTarget:self action:@selector(editClicked:) forControlEvents:UIControlEventTouchUpInside];
//    editBtn.titleLabel.font = FONT(15);
//    editBtn.myHeight = PX(44);
//    editBtn.myWidth = PX(44);
//    _editBtn = editBtn;
//    UIBarButtonItem* editItem = [[UIBarButtonItem alloc] initWithCustomView:editBtn];
//    self.navigationItem.rightBarButtonItem = editItem;
}

-(void)setupSubView{
    
    //列表
    RSRefreshTableView* tableView = [[RSRefreshTableView alloc] initWithFrame:CGRectMake(0, 0, self.view.rs_width, SCREEN_HEIGHT - IPHONE_NAVIGATION_BAR_HEIGHT-IPHONE_TAB_BAR_HEIGHT) style:UITableViewStyleGrouped];
    tableView.refreshEnabled = NO;
    tableView.loadMoreEnabled = NO;
    
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = COLOR_BACKGEOUND;
    tableView.estimatedRowHeight = PX(100);
    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.sectionFooterHeight = CGFLOAT_MIN;
    tableView.sectionHeaderHeight = 10;
    tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
    [tableView registerClass:NSClassFromString(noteBookCell) forCellReuseIdentifier:noteBookCell];
//    tableView.myMargin = 0;
//    tableView.weight = 1.0;
    [self.view addSubview:tableView];
    _tableView = tableView;
    
    LYEmptyView* emptyView = [LYEmptyView emptyActionViewWithImage:NULL titleStr:@"记录每一天的美好时光" detailStr:NULL btnTitleStr:@"去写点什么" target:self action:@selector(addClick:)];
    emptyView.titleLabFont = FONT_FIT(13);
    emptyView.titleLabTextColor = COLOR_GRAY_BASE;
    emptyView.detailLabMargin = 10;
    emptyView.actionBtnFont = FONT_FIT(12);
    emptyView.actionBtnWidth = PX(120);
    emptyView.actionBtnHeight = PX(32);
    emptyView.actionBtnCornerRadius = PX(16);
    emptyView.actionBtnBackGroundColor = COLOR_THEME_A;
    emptyView.actionBtnTitleColor = COLOR_WHITE;
    emptyView.actionBtnMargin = 20;
    emptyView.contentViewOffset = -100;
    tableView.ly_emptyView = emptyView;
    
//    MyLinearLayout* bottomLayout = [MyLinearLayout linearLayoutWithOrientation:(MyOrientation_Horz)];
//    bottomLayout.padding = UIEdgeInsetsMake(8, 16, isIphoneX?IPHONE_BOTTOM_SAFEINSET:8, 16);
//    bottomLayout.myHeight = IPHONE_TAB_BAR_HEIGHT;
//    bottomLayout.gravity = MyGravity_Horz_Fill;
//    bottomLayout.myMargin = 0;
////    [self.contentLayout addSubview:bottomLayout];
//    _bottomLayout = bottomLayout;
//
//    UIButton* allBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [allBtn setTitle:@"全选" forState:UIControlStateNormal];
//    [allBtn setImage:[UIImage imageNamed:@"common_select_n"] forState:UIControlStateNormal];
//    [allBtn setImage:[UIImage imageNamed:@"common_select_h"] forState:UIControlStateSelected];
//    [allBtn setTitleColor:COLOR_GRAY_BASE forState:UIControlStateNormal];
//    allBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 4);
//    allBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 4, 0, 0);
//    allBtn.titleLabel.font = FONT_FIT(14);
//    [allBtn addTarget:self action:@selector(allSelectClicked:) forControlEvents:UIControlEventTouchUpInside];
//    allBtn.myMargin = 0;
//    [allBtn sizeToFit];
//    [bottomLayout addSubview:allBtn];
//    _allBtn = allBtn;
//
//    UIButton* delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [delBtn setTitle:@"删除(0)" forState:UIControlStateNormal];
//    [delBtn setTitleColor:COLOR_RED forState:UIControlStateNormal];
//    delBtn.titleLabel.font = FONT_FIT(14);
//    [delBtn addTarget:self action:@selector(deleteClicked:) forControlEvents:UIControlEventTouchUpInside];
//    delBtn.myMargin = 0;
//    [delBtn sizeToFit];
//    [bottomLayout addSubview:delBtn];
//    _delBtn = delBtn;
//
//    self.bottomLayout.visibility = MyVisibility_Gone;
    
    
    UIButton* addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addBtn setImage:[UIImage imageNamed:@"a_item_add"] forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addClick:) forControlEvents:UIControlEventTouchUpInside];
//    addBtn.titleLabel.font = FONTBOLD_FIT(20);
    addBtn.frame = CGRectMake(self.view.rs_width - 88, CGRectGetMaxY(tableView.frame) - 88, 88, 88);
//    addBtn.layer.cornerRadius = PX(40)/2.0f;
//    addBtn.layer.masksToBounds = YES;
//    addBtn.layer.borderColor = COLOR_THEME_A.CGColor;
//    addBtn.layer.borderWidth = 2.0f;
    
    [self.view addSubview:addBtn];
}

#pragma mark --loadData
- (void)reloadData{
    
    RLMResults* ret = [XNoteBook allObjects];
    
    NSMutableArray* objs = [NSMutableArray array];
    for (int i = 0; i < ret.count; i++) {
        [objs addObject:ret[i]];
    }
    self.noteBooks = objs;
    [self.tableView reloadData];
}

#pragma mark -- actions

- (void)addClick:(UIButton*)sender{
    
    XNoteBookEditViewController* editController = [XNoteBookEditViewController new];
    editController.operation = EditOperation_Add;
    editController.editBlock = ^(id  _Nullable obj, EditOperation operation) {
        [self reloadData];
    };
    [UIViewController showViewController:editController animated:YES];
}

- (void)editClicked:(UIButton*)sender{
    sender.selected = !sender.selected;
    
    self.bottomLayout.visibility = sender.selected?MyVisibility_Visible:MyVisibility_Gone;
    
    for (XNoteBook* obj in self.noteBooks) {
        obj.isSelected = NO;
    }
    
    self.allBtn.selected = NO;
    
    [self.delBtn setTitle:@"删除(0)" forState:UIControlStateNormal];
    
    [self.tableView reloadData];
}

- (void)allSelectClicked:(UIButton*)sender{
    sender.selected = !sender.selected;
    for (XNoteBook* obj in self.noteBooks) {
        obj.isSelected = sender.selected;
    }
    if(sender.selected){
        [self.delBtn setTitle:[NSString stringWithFormat:@"删除(%ld)",self.noteBooks.count] forState:UIControlStateNormal];
    }else{
        [self.delBtn setTitle:@"删除(0)" forState:UIControlStateNormal];
    }
    
    [self.tableView reloadData];
}

- (void)deleteClicked:(UIButton*)sender{
    
    for (XNoteBook* obj in self.noteBooks) {
        if(obj.isSelected){
            RLMResults* ret = [XNoteBook objectsWhere:@"id = %@",obj.id];
            [[RLMRealm defaultRealm] beginWriteTransaction];
            [[RLMRealm defaultRealm] deleteObjects:ret];
            [[RLMRealm defaultRealm] commitWriteTransaction];
        }
    }
    [self reloadData];
    
    [self editClicked:self.editBtn];
}


- (void)checkSelectState{
    
    NSInteger selectCount = 0;
    for (XNoteBook* obj in self.noteBooks) {
        if(obj.isSelected){
            selectCount += 1;
        }
    }
    self.allBtn.selected = selectCount == self.noteBooks.count;
    
    [self.delBtn setTitle:[NSString stringWithFormat:@"删除(%ld)",selectCount] forState:UIControlStateNormal];
}

#pragma mark --UITableViewDelegate  UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.noteBooks.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  
    XNoteBook* noteBook = [self.noteBooks objectAtIndex:indexPath.row];

    XNoteBookTableViewCell* movieCell = [tableView dequeueReusableCellWithIdentifier:noteBookCell forIndexPath:indexPath];
    movieCell.editable = [self isTableEditing];
    movieCell.noteBook = noteBook;
    movieCell.selectBlock = ^(BOOL Bool) {
        [self checkSelectState];
    };
    return movieCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    XNoteBook* noteBook = [self.noteBooks objectAtIndex:indexPath.row];
    
    if([self isTableEditing]){
        noteBook.isSelected = !noteBook.isSelected;
        [self checkSelectState];
        
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationAutomatic)];
    }else{
        /// To Details
        XNoteBookDetailViewController* details = [XNoteBookDetailViewController new];
        details.model = noteBook;
        [UIViewController showViewController:details animated:YES];
    }
}

@end
